///////////////////////////////////////////////////////////////////////////////
// File:        TcpConnectionOutputStream.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "common/TcpConnection.hpp"
#include "common/TcpConnectionOutputStream.hpp"
using namespace monkey::common;

TcpConnectionOutputStream::TcpConnectionOutputStream(TcpConnection& conn)
    : TcpConnectionStream(conn)
{

}

TcpConnectionOutputStream::~TcpConnectionOutputStream()
{

}

int TcpConnectionOutputStream::Flush()
{
    if (Size() <= 0)
        return 0;

    unsigned int bytsTransfered = 0;
    char sendBuf[TCP_CONN_STREAM_SIZE];

    while (Size() > 0)
    {
        unsigned int bytsRead = Peek(sendBuf, TCP_CONN_STREAM_SIZE);
        while (bytsRead > 0)
        {
            int bytsSend = pio_connection_write(conn_.conn_, sendBuf, bytsRead, 0);
            if (bytsSend < 0)
            {
                if (bytsSend == SOCKET_ERROR_WOULDBLOCK)
                    return bytsTransfered;
                else
                    return SOCKET_ERROR;
            }

            bytsTransfered += (unsigned int)bytsSend;

            bytsRead -= (unsigned int)bytsSend;
            Skip((unsigned int)bytsSend);
        }
    }

    return bytsTransfered;
}
